const log = require('../util/log'),
  https = require('https'),
  querystring = require('querystring');

module.exports = (req, res) => {
  const mongoMng = require('../mng/mongoMng')
  if (!mongoMng.db) {
    log('未连接mongo')
    resolve({
      result: -1,
      msg: '系统错误'
    })
    return;
  }
  require('../util/service').handlePost(req, res, (reqObj, resolve) => {
    if (!reqObj.phone || !/^1\d{10}$/.test(reqObj.phone)) {
      resolve({
        result: -1,
        msg: 'phone不合法'
      })
      return
    }
    var collection = mongoMng.db.collection('code');
    var code = ''
    for (var i = 0; i < 4; i++)
      code += Math.floor(Math.random() * 10)
    var data = [{
      phone: reqObj.phone,
      code: code,
      time: require('../../lib/formatDate')(new Date())
    }];
    collection.insert(data, (err, result) => {
      if (err) {
        log(err);
        resolve({
          result: -1,
          msg: '系统错误'
        })
        return;
      }
      resolve({
        result: 1
      })

      var content = querystring.stringify({
        mobile: reqObj.phone,
        message: '验证码:' + code + '【旅悠】'
      });

      var options = {
        host: 'sms-api.luosimao.com',
        path: '/v1/send.json',
        method: 'POST',
        auth: 'api:key-0d8e51e932dfaada327bbf9d9eb5d282',
        agent: false,
        rejectUnauthorized: false,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': content.length
        }
      };

      https.request(options, function (res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
          // log(JSON.parse(chunk));
        });
        res.on('end', function () {
          // log('over');
        });
      }).end(content);
    });
  })
}
